package me.feng.messageinbound
import org.apache.catalina.websocket.MessageInbound
import java.nio.CharBuffer
import java.nio.ByteBuffer
import org.apache.catalina.websocket.WsOutbound
import akka.actor.ActorRef
import akka.actor.ActorSystem
import me.feng.entity.User
import me.feng.entity.Event
import me.feng.entity.EventType
import com.lambdaworks.jacks.JacksMapper
import me.feng.entity.Msg
import me.feng.entity.Message
import java.util.UUID
import me.feng.entity.Letter
import me.feng.entity.LetterType
import org.jsoup.Jsoup
import org.jsoup.safety.Whitelist
import akka.actor.actorRef2Scala
import me.feng.entity.MessageType
import me.feng.actors.MainActor
import me.feng.actors.MainActor

final class MainChart(cid: String, akka: ActorSystem, main: ActorRef) extends MessageInbound {

  var u: User = _

  def getUser() = u
  def setUser(u: User) = { this.u = u }
  def getCid() = cid

  var open: Boolean = _

  override def onClose(status: Int) = {
    // Log
    println("Web Socket Closed: " + status);
    open = false
    if (cid.equals(MainActor.DEFAULT_MAIN_ID))
      main ! new Event(u, MainActor.DEFAULT_MAIN_ID, EventType.CLOSE)
    else
      main ! new Event(u, cid, EventType.EXIT_SESSION)
  }

  // WebSocket握手完成，创建完毕，WsOutbound用于向客户端发送数据
  override def onOpen(outbound: WsOutbound) = {
    // Log
    open = true
    println("Web Socket Open!");
  }


  override def onBinaryMessage(buffer: ByteBuffer) = {
    // Log
    println("Binary Message Receive: " + buffer.remaining());
    // Nothing
  }

  // 有文本消息数据到达
  override def onTextMessage(buffer: CharBuffer) = {
    // Log  链接服务器失败！
    println("Text Message Receive: " + u.id);
    // getWsOutbound可以返回当前的WsOutbound，通过他向客户端回传数据，这里采用的是nio的CharBuffer
    val msg = buffer.toString().replace("\n", "\\n")
    val m = JacksMapper.readValue[Msg](msg)
    val id = UUID.randomUUID().toString().replace("-", "")
    val message = m.t match {
      case 0 => new Message[Letter](MessageType.LETTER, new Letter(id, u, cid, Jsoup.clean(m.msg, Whitelist.relaxed()), LetterType.MAIN))
      case 1 => new Message[Letter](MessageType.LETTER, new Letter(id, u, cid, Jsoup.clean(m.msg, Whitelist.relaxed()), LetterType.USER))
      case 2 => new Message[Letter](MessageType.LETTER, new Letter(id, u, cid, Jsoup.clean(m.msg, Whitelist.relaxed()), LetterType.ROOM))

      // 好友关系处理
      case 10 => {
        if (m.msg.equals("FRIEND_ADD"))
          new Event(u, m.id, EventType.FRIEND_ADD)
      }
    }
    main ! message
  }

}